<script setup>
import {
  Edit,
  Delete
} from '@element-plus/icons-vue'

import { ref, watch } from 'vue'
import {articleListByPageService,articleCateService,addOrAupdateArticleService,delArticleService,editArticleService} from '@/api/article.js'
import {Plus} from '@element-plus/icons-vue'

import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import {useTokenStore} from '@/stores/token.js'
import { ElMessage, ElMessageBox } from 'element-plus'
import { nextTick } from 'vue'
const tokenStore =useTokenStore()
//文章分类数据模型
const categorys = ref([
])

const getCategory = async () => {
  const res = await articleCateService()
  categorys.value = res.data
}
getCategory()


//用户搜索时选中的分类id
const categoryId=ref('')

//用户搜索时选中的发布状态
const state=ref('')

//文章列表数据模型
const articles = ref([
])

//分页条数据模型
const pageNum = ref(1)//当前页
const total = ref(20)//总条数
const pageSize = ref(10)//每页条数

//当每页条数发生了变化，调用此函数
const onSizeChange = (size) => {
  pageSize.value = size
  getArticleListByPage()
}
//当前页码发生变化，调用此函数
const onCurrentChange = (num) => {
  pageNum.value = num
  getArticleListByPage()
}



const getArticleListByPage  = async () => {

  let params = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    categoryId: categoryId.value ? categoryId.value : '',
    state: state.value ? state.value : ''
  }
  let result = await articleListByPageService(params)
  articles.value = result.data.list
  total.value = result.data.total
}

getArticleListByPage()
// 搜索列表
const searchList = () => {
  getArticleListByPage()
}


const reset = () => {
  categoryId.value = ''
  state.value = ''
  getArticleListByPage()
}

//控制抽屉是否显示
const visibleDrawer = ref(false)
//添加表单数据模型
const articleModel = ref({
  title: '',
  categoryId: '',
  coverImg: '',
  content:'',
  state:''
})

// 定义上传请求头
const uploadHeaders = ref({
  Authorization: tokenStore.token // 假设 tokenStore.token 是你的登录凭证
})

// 表单校验规则
const rules = {
  title: [
    { required: true, message: '标题不能为空', trigger: 'blur' },
    { min: 1, max: 16, message: '标题长度为1-16个字符', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择文章分类', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '内容不能为空', trigger: 'blur' }
  ],
  coverImg: [
    { required: true, message: '请上传文章封面', trigger: 'change' }
  ]
}

// 图片上传前的验证
const beforeAvatarUpload = (file) => {
  const isImage = ['image/jpeg', 'image/png', 'image/gif'].includes(file.type)
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('上传图片只能是 JPG/PNG/GIF 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 图片上传成功的回调
const uploadSuccess = (res) => {
  articleModel.value.coverImg = res.data
}

// 表单 ref
const formRef = ref()

// 监听富文本编辑器的内容变化
watch(
  () => articleModel.value.content,
  (newVal) => {
    // 当内容变化时，手动触发表单验证
    if (formRef.value) {
      formRef.value.validateField('content')
    }
  }
)
const editorKey = ref(0)
// 发布文章
const publishArticle = async (state) => {
  articleModel.value.state = state
  // articleModel.value.id = ''
  try {
    await formRef.value.validate()
  }catch {
    ElMessage.error('请完善文章信息')
  }
    // TODO: 这里添加发布文章的API调用
    await addOrAupdateArticleService(articleModel.value)
    ElMessage.success(state === '已发布' ? '发布成功' : '已存为草稿')
    visibleDrawer.value = false
    formRef.value.resetFields()
    getArticleListByPage()
}


const delArticle = async (row) => {
  try {
    await ElMessageBox.confirm('此操作将永久删除该文章, 是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      draggable: true
    })
    await delArticleService(row.id)
    ElMessage.success('删除成功')
    // 如果当前页只有一条数据，且不是第一页，则删除后跳转到上一页
    if (articles.value.length === 1 && pageNum.value > 1) {
      pageNum.value--
    }
    getArticleListByPage()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const editArticle = async (row) => {
  title.value = '编辑文章'
  articleModel.value = row
  visibleDrawer.value = true
  await nextTick() // 等待 Quill 编辑器更新
  formRef.value?.validateField('content')
  editorKey.value++
}

const title = ref()


const OnAddArticle = () => {
  visibleDrawer.value = true;
  title.value = '添加文章'
  articleModel.value = {
    title: '',
    categoryId: '',
    coverImg: '',
    content: '',
    state: ''
  }
  editorKey.value++
}

const onDrawerClosed = () => {
  formRef.value?.resetFields()
  articleModel.value = {
    title: '',
    categoryId: '',
    coverImg: '',
    content: '',
    state: ''
  }
  editorKey.value++
}

</script>
<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>文章管理</span>
        <div class="extra">
          <el-button type="primary" @click="OnAddArticle">添加文章</el-button>
        </div>
      </div>
    </template>
    <!-- 搜索表单 -->
    <el-form inline>
      <el-form-item label="文章分类：">
        <el-select placeholder="请选择" style="width: 240px" v-model="categoryId">
          <el-option
              v-for="c in categorys"
              :key="c.id"
              :label="c.categoryName"
              :value="c.id">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="发布状态：">
        <el-select placeholder="请选择" style="width: 240px" v-model="state">
          <el-option label="已发布" value="已发布"></el-option>
          <el-option label="草稿" value="草稿"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="searchList()">搜索</el-button>
        <el-button @click="reset()">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 文章列表 -->
    <el-table :data="articles" style="width: 100%">
      <el-table-column label="文章标题" width="400" prop="title"></el-table-column>
      <el-table-column label="分类" prop="categoryName"></el-table-column>
      <el-table-column label="发表时间" prop="createTime"> </el-table-column>
      <el-table-column label="状态" prop="state"></el-table-column>
      <el-table-column label="操作" width="100">
        <template #default="{ row }">
          <el-button :icon="Edit" circle plain type="primary" @click="editArticle(row)"></el-button>
          <el-button :icon="Delete" circle plain type="danger" @click="delArticle(row)"></el-button>
        </template>
      </el-table-column>
      <template #empty>
        <el-empty description="没有数据" />
      </template>
    </el-table>
    <!-- 分页条 -->
    <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize" :page-sizes="[3, 5 ,10, 15]"
                   layout="jumper, total, sizes, prev, pager, next" background :total="total" @size-change="onSizeChange"
                   @current-change="onCurrentChange" style="margin-top: 20px; justify-content: flex-end" />

    <!-- 抽屉 -->
    <el-drawer v-model="visibleDrawer" :title="title" direction="rtl" size="50%"  @closed="onDrawerClosed">
      <!-- 添加文章表单 -->
      <el-form :model="articleModel" label-width="100px" :rules="rules" ref="formRef">
        <el-form-item label="文章标题" prop="title">
          <el-input v-model="articleModel.title" placeholder="请输入标题"></el-input>
        </el-form-item>
        <el-form-item label="文章分类" prop="categoryId">
          <el-select placeholder="请选择" v-model="articleModel.categoryId">
            <el-option v-for="c in categorys" :key="c.id" :label="c.categoryName" :value="c.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="文章封面" prop="coverImg">
          <el-upload class="avatar-uploader"
                     :auto-upload="true"
                     :show-file-list="false"
                     action="http://localhost:8080/upload"
                     :headers="uploadHeaders"
                     :on-success="uploadSuccess"
                     :before-upload="beforeAvatarUpload">
            <img v-if="articleModel.coverImg" :src="articleModel.coverImg" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="文章内容" prop="content">
          <div class="editor">
            <quill-editor
                :key="editorKey"
                theme="snow"
                v-model:content="articleModel.content"
                contentType="html"
            >
            </quill-editor>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="publishArticle('已发布')">发布</el-button>
          <el-button type="info" @click="publishArticle('草稿')">草稿</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>

  </el-card>
</template>
<style lang="scss" scoped>
.page-container {
  min-height: 100%;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}

.editor {
  width: 100%;
  :deep(.ql-editor) {
    min-height: 200px;
  }
}
</style>